/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package agenda;

import es.random.agenda.datos.Contacto;
import es.random.java.librerias.gestion.Gestor;
import java.util.TreeSet;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;

/**
 *
 * @author AdminLocal
 */
public class ContactoTableModel extends AbstractTableModel
{

    private Gestor<Contacto> miGestor;

    public ContactoTableModel()
    {
        miGestor = new Gestor<Contacto>();
        miGestor.deserializar();
    }

    @Override
    public int getRowCount()
    {
        if (miGestor != null)
        {
            return miGestor.tamaño();
        } else
        {
            return 0;
        }
    }

    @Override
    public int getColumnCount()
    {
        return miGestor.obtenerNombresColumnas().length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex)
    {
        if (rowIndex >= 0 && columnIndex >= 0)
        {
            return miGestor.obtenerElemento(rowIndex).obtenerElemento(columnIndex);
        }
        else
        {
            return null;
        }
    }

    @Override
    public String getColumnName(int columnIndex)
    {
        return miGestor.obtenerNombresColumnas()[columnIndex];
    }

    @Override
    public Class<?> getColumnClass(int columnIndex)
    {
        return miGestor.obtenerTiposColumnas()[columnIndex];
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex)
    {
        return false;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex)
    {
        miGestor.obtenerElemento(rowIndex).establecerElemento(aValue, columnIndex);
    }

    public void añadirContacto()
    {
        añadirContacto(new Contacto());
    }
    
    public void añadirContacto(Contacto c)
    {
        miGestor.añadirContacto(c);
        this.fireTableDataChanged();
    }

    public void borrarContacto(int i)
    {
        miGestor.borrarContacto(i);
        this.fireTableDataChanged();
    }

    public void guardarCambios()
    {
        miGestor.serializar();
    }

    public void cargarAgenda()
    {
        miGestor.deserializar();
        this.fireTableDataChanged();
    }

    public TreeNode obtenerDatosArbol()
    {
        //DefaultMutableTreeNode nodo = new DefaultMutableTreeNode(miGestor.obtenerElemento(0));
        TreeSet<Contacto> arbol = new TreeSet<Contacto>(miGestor.obtenerDatos());
        //DefaultMutableTreeNode nodo = arbol.first();
        return new DefaultMutableTreeNode(arbol.first());
    }
}
